package com.lzp.java.concurrent.threadlocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ThreadLocal可以解决线程安全问题，给每个线程分配自己的SimpleDateFormat对象
 *
 * @author lzp
 * @date 2020/03/29
 */
public class RrightWaySimpleDateFormater {
    /**
     * 线程池
     */
    public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
    /**
     * 定义ThreadLocal变量--JDK8实现形式
     * 1 使用ThreadLocal初始值设置
     */
    private static ThreadLocal<SimpleDateFormat> dateThreadSafe = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    // JDK7以及之前的实现形式
     private static ThreadLocal<SimpleDateFormat> dateThreadSafe2 = new ThreadLocal<SimpleDateFormat>() {
         @Override
         protected SimpleDateFormat initialValue() {
             return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         }
     };

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
            int finalI = i;
            threadPool.submit(() -> {
                System.out.println(new RrightWaySimpleDateFormater().date(finalI));
            });
        }
        threadPool.shutdown();
    }

    public String date(int seconds) {
        return dateThreadSafe.get().format(new Date(1000 * seconds));
    }

}
